﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Cache;
using System.Drawing;
using System.Text.RegularExpressions;
using Ivony.Web.Html.Parser;
using Ivony.Web.Html;
using Ivony.Web.Html.HtmlAgilityPackAdaptor;
using HtmlAgilityPack;



namespace SimCMS.Common
{
    public static class WebHelper
    {
        /// <summary>
        /// 获取网站内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string CallPage(string url)
        {
            WebResponse response = null;
            Stream stream = null;
            StreamReader reader = null;

            try
            {

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "Get";
                request.KeepAlive = true;
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.Host = "fitness.39.net";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;

                HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

                request.CachePolicy = policy;



                response = request.GetResponse();
                if (!request.HaveResponse)
                {
                    response.Close();
                    return string.Empty;
                }
                stream = response.GetResponseStream();
                Encoding encoding = Encoding.GetEncoding("utf-8");
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            catch (Exception exception)
            {
                throw exception;//TODO
            }
            finally
            {
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (response != null) response.Close();
            }
        }
        /// <summary>
        /// 保存网页图片
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="RootPath"></param>
        /// <returns></returns>
        public static Bitmap Get_img(string Url, string RootPath)
        {
            Bitmap img = null;
            HttpWebRequest req;
            HttpWebResponse res = null;
            try
            {
                System.Uri httpUrl = new System.Uri(Url);
                req = (HttpWebRequest)(WebRequest.Create(httpUrl));
                req.Timeout = 180000; //设置超时值10秒
                req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
                req.Accept = "image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5";
                req.Method = "GET";
                res = (HttpWebResponse)(req.GetResponse());
                img = new Bitmap(res.GetResponseStream());//获取图片流                 
                img.Save(RootPath);//随机名
            }
            catch (Exception ex)
            {
                string aa = ex.Message;
            }
            finally
            {
                if (res != null)
                {
                    res.Close();
                }
            }
            return img;
        }


        /// <summary>
        /// 获取列表页面内容并返回objlist
        /// </summary>
        /// <param name="Html"></param>
        /// <param name="WebPath"></param>
        /// <returns></returns>
        public static List<SimCMS.Model.Simchildobj> GetModelListByHtml(string Html, string WebPath, int ObjType)
        {
            //<(\S*?) [^>]*>.*?</\1>|<.*? />
            List<SimCMS.Model.Simchildobj> List = new List<Model.Simchildobj>();
            var Reg = new Regex(@"<b><a[^>]*href=[""'](?<url>[^""']*?)[""'][^>]*>(?<text>[\w\W]*?)</a></b>", RegexOptions.IgnoreCase);
            //string pattern = @"<a[^>]*href=["'](?<url>[^"']*?)["'][^>]*>(?<text>[\w\W]*?)</a>";
            MatchCollection matchs;
            matchs = Reg.Matches(Html);

            foreach (Match m in matchs)
            {
                SimCMS.Model.Simchildobj Model = new SimCMS.Model.Simchildobj();
                Model.CName = m.Groups["text"].Value;
                Model.Url = m.Groups["url"].Value;
                if (ObjType == 1)
                {
                    Model.Pic = "/img/food/" + Model.CName + ".jpg";
                    Get_img("http://fitness.39.net/tzgj/static/log_newfoodcn/" + Model.CName + ".jpg", WebPath + Model.Pic);
                }
                else if (ObjType == 2)
                {
                    Model.Pic = "/img/sport/" + Model.CName + ".jpg";
                    Get_img("http://fitness.39.net/tzgj/static/sport/" + Model.CName + ".jpg", WebPath + Model.Pic);
                }


                List.Add(Model);
            }
            return List;
        }

        /// <summary>
        /// 获取food detail信息
        /// </summary>
        /// <param name="objModel"></param>
        /// <param name="AttrList"></param>
        /// <param name="SAttrList"></param>
        /// <returns></returns>
        public static SimCMS.Model.Simchildobj GetDetailInformation(SimCMS.Model.Simchildobj objModel, List<SimCMS.Model.Simobjattr> AttrList)
        {
            if (!objModel.Url.Contains("list"))
            {
                string Html = CallPage(objModel.Url);
                var Reg = new Regex(@"<li><span>(?<Attr>[\w\W]*?)</span>(?<value>[\w\W]*?)</li>");
                MatchCollection matchs;
                matchs = Reg.Matches(Html);
                List<SimCMS.Model.Simchildobjvalue> valuelist = new List<Model.Simchildobjvalue>();
                foreach (Match m in matchs)
                {
                    var AttrModel = AttrList.Where(o => o.AttrName == m.Groups["Attr"].Value.Trim().Replace("：", "")).FirstOrDefault();
                    if (AttrModel != null)
                    {
                        if (!valuelist.Any(o => o.AttrId == AttrModel.Id))
                        {
                            SimCMS.Model.Simchildobjvalue valueModel = new Model.Simchildobjvalue();
                            valueModel.AttrId = AttrModel.Id;
                            var Values = m.Groups["value"].Value.Trim().Replace("<i>", "").Replace("</i>", "");
                            if (Values.Contains("微克"))
                            {
                                valueModel.Unit = "微克";
                                valueModel.AttrValue = Values.Replace("微克", "");
                            }
                            else if (Values.Contains("毫克"))
                            {
                                valueModel.Unit = "毫克";
                                valueModel.AttrValue = Values.Replace("毫克", "");
                            }
                            else if (Values.Contains("克"))
                            {
                                valueModel.Unit = "克";
                                valueModel.AttrValue = Values.Replace("克", "");
                            }
                            else if (Values.Contains("大卡"))
                            {
                                valueModel.Unit = "大卡";
                                valueModel.AttrValue = Values.Replace("大卡", "");
                            }
                            else
                            {
                                valueModel.Unit = "-";
                                valueModel.AttrValue = Values;
                            }
                            valueModel.Simchildobj = objModel;
                            valuelist.Add(valueModel);
                        }
                    }
                }
                objModel.Simchildobjvalue = valuelist;
            }
            else
            {
                return null;
            }

            return objModel;
        }

        public static List<SimCMS.Model.SimFCategory> GetCateList(string Url)
        {
            List<SimCMS.Model.SimFCategory> ArrList = new List<Model.SimFCategory>();
            var Client = new WebClient();
            Client.Encoding = Encoding.GetEncoding("utf-8");
            var html = Client.DownloadString(Url);
            var parser = new JumonyParser();
            var document = parser.Parse(html);
            var MainAList = document.Find("a[rel=\"jcc\"]");
            //class=" normal bold"
            foreach (var MainA in MainAList)
            {
                var Model = new SimCMS.Model.SimFCategory() { Id = ArrList.Count + 1, Fid = 0, FCateName = MainA.InnerText(), Url = MainA.Attribute("href").Value().Trim('/') };
                ArrList.Add(Model);
                ArrList = NextChildCate(ArrList, MainA.Parent.NextElement(), Model.Id);

            }
            var ChildModelList = document.Find("a[rel=\"cpdq\"]");
            foreach (var ChildModel in ChildModelList)
            {
                var childCate = new SimCMS.Model.SimFCategory() { Id = ArrList.Count + 1, FCateName = ChildModel.InnerText(), Url = ChildModel.Attribute("href").Value().Trim('/') };
                if (!ArrList.Any(o => o.FCateName == childCate.FCateName))
                {
                    ArrList.Add(childCate);
                }

            }
            return ArrList;
        }

        public static List<SimCMS.Model.SimFoodmenu> MenuList(string Url, List<SimCMS.Model.SimFoodmenu> ArrList, int Fid, string WebPath)
        {
            if (ArrList == null)
            {
                ArrList = new List<Model.SimFoodmenu>();
            }
            var Client = new WebClient();
            Client.Encoding = Encoding.GetEncoding("utf-8");
            var html = Client.DownloadString(Url);
            var parser = new JumonyParser();
            var document = parser.Parse(html);
            var MenuAList = document.Find("a[class=\"shipu\"]");
            foreach (var MenuA in MenuAList)
            {
                if (ArrList.Any(o => o.FMenuName == MenuA.Attribute("title").Value()))
                {
                    var Cid = ArrList.Where(o => o.FMenuName == MenuA.Attribute("title").Value()).FirstOrDefault().Cid;
                    if (!Cid.Split(',').Any(o => o == Fid.ToString()))
                    {
                        ArrList.Where(o => o.FMenuName == MenuA.Attribute("title").Value()).FirstOrDefault().Cid = Cid + "," + Fid.ToString();
                    }
                }
                else
                {
                   
                    var PicUrl = MenuA.Find("img").FirstOrDefault().Attribute("src").Value();
                    var Title = MenuA.Attribute("title").Value();
                    Get_img(PicUrl, WebPath + "/img/foodmenu/" + Title + ".jpg");
                    var Model = new SimCMS.Model.SimFoodmenu() {  FMenuName = Title, Pic = "/img/foodmenu/" + Title + ".jpg", Cid = Fid.ToString(), Url = MenuA.Attribute("href").Value().Trim('/') };
                    ArrList.Add(Model);
                    
                }
            }
            var NextModel = document.Find("a[rel=\"next\"]").FirstOrDefault();
            if (NextModel != null)
            {
                ArrList = MenuList("http://www.xinshipu.com/" + NextModel.Attribute("href").Value(), ArrList, Fid, WebPath);
            }
            return ArrList;
        }

        public static List<SimCMS.Model.SimFCategory> NextChildCate(List<SimCMS.Model.SimFCategory> CateModelList, IHtmlElement Element, int Fid)
        {

            if (Element != null && Element.Attribute("rel").Value() == "cpdq")
            {
                var childCate = new SimCMS.Model.SimFCategory() { Id = CateModelList.Count + 1, Fid = Fid, FCateName = Element.InnerText(), Url = Element.Attribute("href").Value().Trim('/') };
                CateModelList.Add(childCate);
                CateModelList = NextChildCate(CateModelList, Element.NextElement(), Fid);
            }
            else if (Element != null && Element.Name == "br")
            {
                CateModelList = NextChildCate(CateModelList, Element.NextElement(), Fid);
            }
            return CateModelList;
        }

        public static SimCMS.Model.SimFoodmenu GetfoodMenuDetailWeb(SimCMS.Model.SimFoodmenu foodMenu, string WebPath, string Url)
        {
            try
            {
                var Client = new WebClient();
                Client.Encoding = Encoding.GetEncoding("utf-8");
                var html = Client.DownloadString(Url);
                var parser = new JumonyParser();
                var document = parser.Parse(html);
                var H2 = document.Find("h2[class=\"no-bottom orange\"]");
                var TitleModel = document.Find("img[class=\"photo\"]").FirstOrDefault();
                string ImageUrl = TitleModel.Attribute("src").Value();
                string Title = TitleModel.Attribute("title").Value();
                foodMenu.FMenuName = Title;
                //Get_img(ImageUrl, WebPath + "/img/foodmenu/" + Title + ".jpg");
                // foodMenu.Pic = WebPath + "/img/foodmenu/" + Title + ".jpg";
                foreach (var h in H2)
                {
                    string Hname = h.InnerText();
                    if (Hname == "材料")
                    {
                        var PContent = getElement(h, "P");
                        foodMenu.Material = PContent;
                        var List = h.SiblingNodesAfterSelf();
                        StringBuilder sb = new StringBuilder();
                        foreach (var mode in List)
                        {
                            if (mode.RawHtml != null)
                            {
                                sb.Append(mode.RawHtml.Replace("\t", "").Replace("\n", ""));
                            }
                        }
                        foodMenu.Detail = sb.ToString();
                    }
                }
            }
            catch(Exception ex)
            {
                foodMenu.Detail = ex.ToString();
                foodMenu.Material = "Error";
            }
            return foodMenu;
        }

        public static string getElement(IHtmlElement h, string findElementName)
        {
            if (h.Name.ToUpper() == findElementName)
            {
                return h.InnerText();
            }
            else
            {

                return getElement(h.NextElement(), findElementName);
            }

        }

        public static string getAllElementText(IHtmlNode h, StringBuilder sb)
        {
            if (h.NodeObject.ToString() == "TEXTNODE")
            {
                sb.Append(h.InnerText());
                if (h.NextNode() != null)
                {
                    getAllElementText(h.NextNode(), sb);
                }
            }
            else
            {
                if (h.NextElement() != null)
                {
                    getAllElementText(h.NextElement(), sb);
                }
            }
            return sb.ToString();
        }

        public static SimCMS.Model.Simchildobj GetSportDetailInformation(SimCMS.Model.Simchildobj objModel, List<SimCMS.Model.Simobjattr> AttrList)
        {
            // met/
            //总分钟=30/met
            if (!objModel.Url.Contains("list"))
            {
                string Html = CallPage(objModel.Url);
                var Reg = new Regex(@"<cite>(?<text>[\w\W]*?)</cite>", RegexOptions.IgnoreCase);
                MatchCollection matchs;
                matchs = Reg.Matches(Html);
                List<SimCMS.Model.Simchildobjvalue> valuelist = new List<Model.Simchildobjvalue>();
                foreach (Match m in matchs)
                {
                    #region
                    float mesument = 0;
                    float met = 0;
                    var AttrModel = AttrList.Where(o => o.AttrName == "消耗").FirstOrDefault();
                    if (AttrModel != null)
                    {
                        if (!valuelist.Any(o => o.AttrId == AttrModel.Id))
                        {
                            SimCMS.Model.Simchildobjvalue valueModel = new Model.Simchildobjvalue();
                            valueModel.AttrId = AttrModel.Id;
                            var Values = m.Groups["text"].Value.Trim();
                            valueModel.Unit = "卡";
                            valueModel.AttrValue = Values.Replace("卡", "");
                            mesument = int.Parse(valueModel.AttrValue);
                            valueModel.Simchildobj = objModel;
                            valuelist.Add(valueModel);
                        }
                    }
                    var AttrModel1 = AttrList.Where(o => o.AttrName == "MET").FirstOrDefault();
                    if (AttrModel1 != null)
                    {
                        if (!valuelist.Any(o => o.AttrId == AttrModel1.Id))
                        {
                            SimCMS.Model.Simchildobjvalue valueModel1 = new Model.Simchildobjvalue();
                            valueModel1.AttrId = AttrModel1.Id;
                            valueModel1.Unit = "MET";
                            met = float.Parse((mesument / 60).ToString());
                            valueModel1.AttrValue = met.ToString("0.0");
                            valueModel1.Simchildobj = objModel;
                            valuelist.Add(valueModel1);
                        }
                    }
                    var AttrModel2 = AttrList.Where(o => o.AttrName == "分钟").FirstOrDefault();
                    if (AttrModel2 != null)
                    {
                        if (!valuelist.Any(o => o.AttrId == AttrModel2.Id))
                        {
                            SimCMS.Model.Simchildobjvalue valueModel2 = new Model.Simchildobjvalue();
                            valueModel2.AttrId = AttrModel2.Id;
                            valueModel2.Unit = "分钟";
                            valueModel2.AttrValue = (30 / met).ToString("0.0");
                            valueModel2.Simchildobj = objModel;
                            valuelist.Add(valueModel2);
                        }
                    }
                    #endregion
                }
                objModel.Simchildobjvalue = valuelist;
            }
            else
            {
                return null;
            }

            return objModel;
        }
    }
}
